/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use crate::common::ErrorCode;
use crate::log_e;
use crate::traits::edit_session::EditSession;
use crate::traits::edit_session_manager::EditSessionManager;
use crate::Challenge;

pub struct DefaultEditSessionManager {
    edit_session: Option<EditSession>,
}

impl DefaultEditSessionManager {
    pub fn new() -> Self {
        DefaultEditSessionManager {
            edit_session: None,
        }
    }
}

impl EditSessionManager for DefaultEditSessionManager {
    fn open_edit_session<'a>(&'a mut self, user_id: i32) -> Result<&'a mut EditSession, ErrorCode> {
        if self.edit_session.is_some() {
            log_e!("Edit session already exists");
            return Err(ErrorCode::GeneralError);
        }

        let session = EditSession::new(user_id)?;
        self.edit_session = Some(session);
        Ok(self.edit_session.as_mut().unwrap())
    }

    fn close_edit_session(&mut self) {
        self.edit_session = None;
    }

    fn get_edit_session<'a>(&'a mut self) -> Result<&'a mut EditSession, ErrorCode> {
        if self.edit_session.is_none() {
            log_e!("No active edit session found");
            return Err(ErrorCode::GeneralError);
        }

        Ok(self.edit_session.as_mut().unwrap())
    }

    fn check_session_valid(&mut self, user_id: i32) -> Result<(), ErrorCode> {
        let edit_session = self.get_edit_session()?;
        edit_session.check_valid(Some(user_id))
    }

    fn get_session_challenge(&mut self, user_id: i32) -> Result<Challenge, ErrorCode> {
        self.check_session_valid(user_id)?;
        let edit_session = self.get_edit_session()?;
        Ok(*edit_session.challenge())
    }

    fn check_challenge(&mut self, user_id: i32, challenge: Challenge) -> Result<(), ErrorCode> {
        let edit_session = self.get_edit_session()?;
        edit_session.check_valid(Some(user_id))?;
        if challenge != *edit_session.challenge() {
            return Err(ErrorCode::BadMatch);
        }
        Ok(())
    }
}
